﻿using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Const;
using Entitas;
using UnityEngine;

public class SlideSystem : ReactiveSystem<InputEntity>
{
    private Contexts _contexts;
    public SlideSystem(Contexts context) : base(context.input)
    {
        _contexts = context;
    }

    protected override ICollector<InputEntity> GetTrigger(IContext<InputEntity> context)
    {
        return context.CreateCollector(InputMatcher.ComponentsSlide);
    }

    protected override bool Filter(InputEntity entity)
    {
        return entity.hasComponentsSlide;
    }
    protected override void Execute(List<InputEntity> entities)
    {
        if (entities.Count == 1)
        {
            InputEntity entity = entities.SingleEntity();
            customData pos=new customData(
                entity.componentsSlide.ClickPos.x,
                entity.componentsSlide.ClickPos.y
                );
            bool isMovable = _contexts.game
                .GetEntitiesWithComponentsItemIndex(pos)
                .SingleEntity().isComponentsMovable;

            if (isMovable)
            {
                var nextPos = NextPos(entity);
                _contexts.input.ReplaceComponentsClick(nextPos.x,nextPos.y);
                //TODO:交换Item
                
            }
        }
    }

    private customData NextPos(InputEntity entity)
    {
        int x = entity.componentsSlide.ClickPos.x;
        int y = entity.componentsSlide.ClickPos.y;
        
        switch(entity.componentsSlide.SlideDirection)
        {
            case slideDirection.UP:
                y++;
                break;
            case slideDirection.DOWN:
                y--;
                break;
            case slideDirection.RIGHT:
                x++;
                break;
            case slideDirection.LEFT:
                x--;
                break;
        }

        x = LimitValue(x, 0, _contexts.game.componentsGameBoardComponents.columns-1);
        y = LimitValue(y, 0, _contexts.game.componentsGameBoardComponents.raws-1);
        return new customData(x,y);
    }

    private int LimitValue(int value, int min, int max)
    {
        if (value < min)
        {
            value = min;
        }

        if (value > max)
        {
            value = max;
        }

        return value;
    }
}
